package com.ruoyi.apiserver.utils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * AES加密工具类
 */
public class AESUtils {
    
    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
    
    /**
     * 生成AES密钥
     * @return Base64编码的密钥
     * @throws Exception
     */
    public static String generateKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        keyGenerator.init(128);
        SecretKey secretKey = keyGenerator.generateKey();
        return Base64.getEncoder().encodeToString(secretKey.getEncoded());
    }
    
    /**
     * AES加密
     * @param content 待加密内容
     * @param key 密钥(Base64编码)
     * @return 加密后的内容(Base64编码)
     * @throws Exception
     */
    public static String encrypt(String content, String key) throws Exception {
        // 如果key是十六进制字符串，需要转换为字节数组
        byte[] keyBytes;
        if (key.length() == 32) {
            // 128位密钥（16字节）
            keyBytes = hexStringToByteArray(key);
        } else {
            // 否则认为是Base64编码的密钥
            keyBytes = Base64.getDecoder().decode(key);
        }
        
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, ALGORITHM);
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] encrypted = cipher.doFinal(content.getBytes("UTF-8"));
        return Base64.getEncoder().encodeToString(encrypted);
    }
    
    /**
     * AES解密
     * @param content 待解密内容(Base64编码)
     * @param key 密钥
     * @return 解密后的内容
     * @throws Exception
     */
    public static String decrypt(String content, String key) throws Exception {
        // 如果key是十六进制字符串，需要转换为字节数组
        byte[] keyBytes;
        if (key.length() == 32) {
            // 128位密钥（16字节）
            keyBytes = hexStringToByteArray(key);
        } else {
            // 否则认为是Base64编码的密钥
            keyBytes = Base64.getDecoder().decode(key);
        }
        
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, ALGORITHM);
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(content));
        return new String(decrypted, "UTF-8");
    }
    
    /**
     * 将十六进制字符串转换为字节数组
     * @param hexString 十六进制字符串
     * @return 字节数组
     */
    private static byte[] hexStringToByteArray(String hexString) {
        int len = hexString.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
                    + Character.digit(hexString.charAt(i+1), 16));
        }
        return data;
    }
}